import { defineStore } from "pinia";
import { userLogin, addressPost, addressGet, addressPut } from "./../api/user";
import { useCart } from "./cart";
import { UserType, UserInfoType, AddressType } from "../types/user";
import router from "../router/index";

interface UserState {
  userInfo: UserInfoType | null;
}
//用户信息
export const useUserStore = defineStore("user-store", {
  state: (): UserState => ({
    userInfo: null,
  }),
  actions: {
    //带异步请求的action
    async userLoginAction(user: UserType) {
      let res = await userLogin(user);
      // console.log(res);
      this.userInfo = res.data;
      localStorage.setItem("userInfo", JSON.stringify(res.data));
      router.push("/home");
      const cart = useCart();
      //触发action从数据库请求购物车数据
      cart.cartInitAction();
    },
  },
});

//收货地址
interface AddressState {
  list: Array<AddressType>;
  chosenId: string;
}
export const useAddress = defineStore("address", {
  state: (): AddressState => ({
    list: [
      // {
      //   id: "1",
      //   name: "张三",
      //   tel: "13000000000",
      //   address: "浙江省杭州市西湖区文三路 138 号东方通信大厦 7 楼 501 室",
      //   isDefault: true,
      // }
    ],
    chosenId: "1",
  }),
  actions: {
    async addressAddAction(addressObj: AddressType) {
      let res = await addressPost(addressObj);
      console.log(res);
      let { province, city, county, addressDetail } = addressObj;
      addressObj.address = province + city + county + addressDetail;
      this.list.push(addressObj);
    },
    //初始化地址列表
    async addressInitAction() {
      const user = useUserStore();
      let userid = user?.userInfo?.objectId;
      if (userid) {
        let res = await addressGet(userid);
        let { results } = res.data;
        results.forEach((item: AddressType) => {
          let { province, city, county, addressDetail } = item;
          item.address = province + city + county + addressDetail;
        });
        this.list = results;
      }
    },
    //更新地址
    async addressUpdateAction(objectId: string, addressObj: AddressType) {
      let res = await addressPut(objectId, addressObj);
      console.log(res);
    },
  },
});
